package net.wicp.tams.plugin.task.svn;

import java.io.File;
import java.util.Date;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.tmatesoft.svn.core.SVNDepth;
import org.tmatesoft.svn.core.wc.SVNClientManager;
import org.tmatesoft.svn.core.wc.SVNRevision;

import net.wicp.tams.common.others.SVNUtil;
import net.wicp.tams.commons.apiext.StringUtil;
import net.wicp.tams.commons.constant.DateFormatCase;

/**
 * 把项目中的代码加到SVN中
 */
@Mojo(name = "addsvn")
public class AddSVN extends AbstractMojo {
	// 项目目录
	@Parameter(defaultValue = "${project.basedir}/", required = false)
	private String basedir;

	// 生产、预发环境下的用户名、密码，中间用逗号隔开
	@Parameter(defaultValue = "maven_build,maven_build", required = false, property = "user")
	private String user;

	// 要上传的SVN地址
	@Parameter(property = "svn", required = true)
	private String svn;

	@Override
	public void execute() throws MojoExecutionException, MojoFailureException {
		if (StringUtil.isNull(user)) {
			throw new MojoFailureException("必须传入用户：用户名、密码中间用逗号（,）隔开");
		}
		String[] userary = user.split(",");
		if (ArrayUtils.isEmpty(userary) || userary.length < 2) {
			throw new MojoFailureException("用户格式不对，正确的格式为：用户名,密码");
		}
		SVNUtil svnobj = SVNUtil.getInstance();
		SVNClientManager clientManager = svnobj.authSvn(svn, userary[0], userary[1]);
		File workDir = new File(basedir);
		if (!svnobj.isWorkingCopy(workDir)) {
			svnobj.checkout(clientManager, svn, SVNRevision.HEAD, workDir, SVNDepth.fromRecurse(false));
			svnobj.checkVersiondDirectory(clientManager, workDir);
			svnobj.commit(clientManager, workDir, true,
					"提交SVN,时间:" + DateFormatCase.yyyyMMddHHmmss.getInstanc().format(new Date()));
			getLog().info("-----提交成功-----");
		} else {
			svnobj.overWrite(clientManager, workDir, svn);
		}

	}

}
